//
//  HMHorizontalGridView.m
//  Pods
//
//  Created by WangYong on 2017/9/12.
//
//

#import "HMHorizontalGridView.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>

//.h
@interface HMHorizontalGridViewLayout : UICollectionViewLayout

@property (assign,nonatomic) NSInteger column;

@property (assign,nonatomic) NSInteger row;

//获取一共多少页
- (NSInteger) numberOfPages;

@end

//.m

@interface HMHorizontalGridViewLayout ()

@property (assign ,nonatomic) CGSize contentSize;

//存储的布局属性容器
@property (strong ,nonatomic) NSMutableArray <UICollectionViewLayoutAttributes*>* attributes;

@end

@implementation HMHorizontalGridViewLayout

- (NSMutableArray<UICollectionViewLayoutAttributes *> *)attributes
{
    if (_attributes == nil) {
        _attributes = [NSMutableArray array];
    }
    return _attributes;
}

//获取一共多少项
- (NSInteger)numberOfItems{
    return [self.collectionView numberOfItemsInSection:0];
}

//获取一共多少页
- (NSInteger)numberOfPages{
    //每页多少项目
    NSInteger numberOfItemInPerPage = self.column * self.row;
    NSInteger allCount = [self numberOfItems];

    //floor向下取整
    return (allCount % numberOfItemInPerPage) == 0 ? (allCount / numberOfItemInPerPage) : (floorf(allCount * 1.0 / numberOfItemInPerPage) + 1);
}

- (void)prepareLayout{
    //1.1计算出有多少页
    NSInteger pageCount = [self numberOfPages];

    //1.2计算contentSize
    self.contentSize = CGSizeMake(self.collectionView.frame.size.width * pageCount, self.collectionView.frame.size.height);

    //2.预先计算好cell的大小
    NSInteger width = self.collectionView.frame.size.width / self.column;
    NSInteger height = self.collectionView.frame.size.height / self.row;

    //循环页数
    for (NSInteger i = 0; i < pageCount; i++) {
        //循环行数
        for (NSInteger rowIndex = 0; rowIndex < self.row; rowIndex ++) {
            //循环列数
            for (NSInteger columnIndex = 0 ; columnIndex < self.column; columnIndex ++) {
                NSInteger itemIndex = i * self.row * self.column + rowIndex * self.column + columnIndex;

                //2.1创建一个布局属性,必须设置section
                UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForRow:itemIndex inSection:0]];

                CGFloat x = floor(itemIndex * 1.0 / (self.row * self.column)) +columnIndex * width + i * self.collectionView.frame.size.width;
                CGFloat y = (rowIndex % self.row) * height;

                //2.2为布局属性增加新属性
                attribute.frame = CGRectMake(x, y, width, height);

                //2.3把计算好的属性添加到计算容器中
                [self.attributes addObject:attribute];
                if (itemIndex >= [self numberOfItems]-1) {
                    return;
                }
            }
        }
    }

}

//返回当前collectionView所需要的contentSize
- (CGSize)collectionViewContentSize{
    return self.contentSize;
}

//当滚动到视图可见区域时,所需的布局属性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    NSMutableArray *att = [NSMutableArray array];

    //过滤与rect相交的布局属性
    [self.attributes enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (CGRectIntersectsRect(rect, obj.frame)) {
            [att addObject:obj];
        }
    }];
    return att;
}

@end

//.h
@interface HMHorizontalGridViewCell : UICollectionViewCell

@property(strong ,nonatomic) UIImageView *iconImageView;

@property(strong ,nonatomic) UILabel *titleLabel;

@end

//.m

@implementation HMHorizontalGridViewCell

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];

    if (self) {
        CGFloat width = 50;

        self.contentView.backgroundColor = [UIColor clearColor];
        self.contentView.clipsToBounds = YES;

        self.iconImageView = [UIImageView new];
        self.iconImageView.contentMode = UIViewContentModeScaleAspectFill;
        self.iconImageView.clipsToBounds = YES;
        self.iconImageView.layer.cornerRadius = width/2;

        [self.contentView addSubview:self.iconImageView];

        self.titleLabel = [UILabel new];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:13];
        self.titleLabel.textColor = [UIColor blackColor];

        [self.contentView addSubview:self.titleLabel ];

        //布局
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.contentView);
            make.height.mas_equalTo(30);
            make.bottom.mas_equalTo(0);
        }];

        [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.contentView);
            make.bottom.equalTo(self.titleLabel.mas_top).offset(0);
            make.width.height.mas_equalTo(width);
        }];
    }

    return self;
}



@end

@interface HMHorizontalGridView ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>

@property(strong ,nonatomic) UICollectionView *collectionView;

@property (strong ,nonatomic) UIPageControl *pageControl;

//自定义布局对象
@property (strong ,nonatomic)HMHorizontalGridViewLayout *customLayout;

@end

@implementation HMHorizontalGridView{
    //数量
    NSInteger _count;
}

- (UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        //系统流式布局无法满足,需要自定义布局
        self.customLayout = [HMHorizontalGridViewLayout new];

        NSInteger row = 2;
        NSInteger column = 5;

        if (self.delegate &&[self.delegate respondsToSelector:@selector(numberOfRowsInHorizontalGridView:)]) {
            row = [self.delegate numberOfRowsInHorizontalGridView:self];
        }

        if (self.delegate &&[self.delegate respondsToSelector:@selector(numberOfColumnsInHorizontalGridView:)]) {
            column = [self.delegate numberOfColumnsInHorizontalGridView:self];
        }

        self.customLayout.row = row;
        self.customLayout.column = column;

        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.customLayout ];

        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[HMHorizontalGridViewCell class] forCellWithReuseIdentifier:@"CELL"];
        [self addSubview:_collectionView];

        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self);
            make.bottom.equalTo(self.pageControl.mas_top);
        }];
    }
        return _collectionView;
}

- (UIPageControl *)pageControl{
    if (_pageControl == nil) {
        _pageControl = [UIPageControl new];
        [self addSubview:_pageControl];

        [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self);
            make.height.mas_equalTo(30);
        }];
    }
    return  _pageControl;
}

//刷新
- (void)reloadData{
    _count = 0;

    if (self.datasource && [self.datasource respondsToSelector:@selector(numberOfItemInHorizontalGridView:)]) {
        _count = [self.datasource numberOfItemInHorizontalGridView:self];
    }

    self.pageControl.pageIndicatorTintColor = [UIColor grayColor];

    if (self.mainColor) {
        self.pageControl.currentPageIndicatorTintColor = self.mainColor;
    }else
    {
        self.pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
    }

    [self.collectionView reloadData];

    self.pageControl.currentPage = 0;
    self.pageControl.numberOfPages = [self.customLayout numberOfPages];
}

#pragma mark - UICollectionViewDataSource - 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HMHorizontalGridViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];

    //标题
    if (self.datasource && [self.datasource respondsToSelector:@selector(horizontalGridView:titleForItemAtIndex:)]) {
        cell.titleLabel.text = [self.datasource horizontalGridView:self titleForItemAtIndex:indexPath.row];
    }

    //图片
    if (self.datasource &&[self.datasource respondsToSelector:@selector(horizontalGridView:urlForItemAtIndex:)]) {
        NSURL *url = [self.datasource horizontalGridView:self urlForItemAtIndex:indexPath.row];

        if (url != nil) {
            if (self.defaultImage == nil) {
                [cell.iconImageView sd_setImageWithURL:url];
            }else{
                [cell.iconImageView sd_setImageWithURL:url placeholderImage:self.defaultImage];
            }
        }
    }
    return cell;
}

#pragma mark - UICollectionViewDelegate - 
//该方法在 UICollectionViewFlowLayout 中
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(80, 80);
}

#pragma mark - UIScrollViewDelegate - 
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = scrollView.contentOffset.x / scrollView.frame.size.width;
}




@end
